<?php
/**
 * Celebrio Kernel
 *
 * @copyright  Copyright (c) 2012 Celebio Software, s.r.o.
 * @package    Kernel
 */
namespace KernelModule\LogsModule\LoggerModule;

use Nette\Object;
use Nette\Environment;
use Nette\String;
use KernelModule\LogsModule\LoggerModule\ILogReader;
use Celebrio\FileSystem\TextFile;
use Celebrio\Logging\Logger;

/**
 * Interface for reading logs in Celebrio
 * 
 * @author Martin Novák
 */
class LogReaderFile extends Object implements ILogReader {
    
	/**
	 * returns array with stored logs
	 * array(
	 *	  "id" => mixed,
	 *	  "time" => date("D, d M Y H:i:s"),
	 *	  "level" => string,
	 *	  "file" => string,
	 *	  "class" => string,
	 *	  "method" => string,
	 *	  "line" => int,
	 *	  "message" => string)
	 * @param string $target name of target table or file
	 * @param mixed $from start reading from
	 * @return array
	 */
    public static function getLogsList($target,$from = NULL) {
    	$results = array();
    	$logDir = Environment::expand("%logDir%");
        if (!String::endsWith($logDir, "/")) {
        	$logDir = $logDir . "/";
        }
        if(file_exists($logDir.$target.".log")) {
	        $logFile = NULL;
	    	try {
	    		$logFile = new TextFile($logDir.$target.".log");
	    	} catch (\FileNotFoundException $ex) {
	    		\Logger::getRootLogger()->error($logDir.$target.".log not found",$ex);
	    		return 0;
	    	}
	    	
	    	$i = 0;
	    	$id = $from;
       	 	while($line = $logFile->getLine()) {
       	 		$log = explode("§", $line);
	        	$results[] = array(
		    				"id" => $id,
		    				"time" => $log[0],
		    				"level" => next($log),
		    				"file" => next($log),
		    				"class" => next($log),
		    				"method" => next($log),
		    				"line" => next($log),
		    				"message" => next($log));
	    		$i++;
	    		$id++;
	    		if($i==50) break;
        	}
        }
        
        return $results;
    }

}